<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login-form" :model="loginForm" :rules="rules" ref="loginFormRef">
          <h1>Hello</h1>
          <h2>欢迎使用M运营平台</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="login-btn" type="primary" @click="login" :loading="loading">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup name="Login">
import { ref, reactive } from 'vue'
import { User, Lock, Hide } from '@element-plus/icons-vue'
import useUserStore from '@/stores/modules/user'
import { useRouter } from 'vue-router'
import { ElNotification, FormRules } from 'element-plus'
let useStore = useUserStore()

let loginForm = reactive({
  username: '',
  password: ''
})
let loading = ref(false)
// 获取el-form示例组件
let loginFormRef = ref()
// 获取路由器
let router = useRouter()

const rules = reactive({
  username: [{ required: true, trigger: 'blur', message: '账号不可为空' }],
  password: [
    { required: true, message: '密码不可为空' },
    { min: 3, max: 12, trigger: 'change', message: '密码长度在3~12之间' }
    // { validator: validatePwd, trigger: 'change' },
  ]
})
// 表单自定义校验函数
function validatePwd(rule, value, callback) {
  console.log(rule, value, callback)
}
const login = async () => {
  let formRes = await loginFormRef.value.validate()
  if (!formRes) {
    return
  }
  loading.value = true
  try {
    await useStore.userLogin(loginForm)
    loading.value = false
    router.push('/')
    ElNotification({
      type: 'success',
      message: '登录成功'
    })
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: error.message
    })
  }
}
</script>

<style scoped lang="scss">
.login-container {
  background-color: pink;
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login-form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url('@/assets/images/login_form.png');
    background-size: cover;
    padding: 40px;

    h1 {
      color: #fff;
    }
    h2 {
      color: #fff;
      margin: 10px 0;
    }

    .login-btn {
      width: 100%;
    }
  }
}
</style>
